package com.wlz.http;

import com.alibaba.fastjson.JSONObject;
import com.wlz.entity.request.f1.F1Request;
import com.wlz.util.ExcelUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.util.List;

/**
 * @author wlz
 * @date 2022-11-26  1:20 上午
 */
@Slf4j
public class OkHttpF1 {

//    private static final String URL = "http://127.0.0.1:9978/tbox-api-b60v/f1";

    private static final String URL = "https://otaapi.bjev.com.cn/tbox-api-b60v/api/fota/f1";

    private static final String FILE_URL = "/Users/wlz/Desktop/618台车_OTA平台上报信息.xlsx";

    public static void main(String[] args) throws IOException, InterruptedException {
        List<F1Request> f1Requests = ExcelUtils.getF1Request(FILE_URL);
        int count = 0;
        int successCount = 0;
        if (f1Requests != null && f1Requests.size() > 0) {
            for (F1Request f1Request : f1Requests) {
                Response response = sendHttp(JSONObject.toJSONString(f1Request));
                count++;
//                Thread.sleep(500);
                JSONObject result = JSONObject.parseObject(response.body().string());
                if (100 == result.getInteger("code")) {
                    successCount++;
                }
                log.info("VIN {}  response body {}", f1Request.getHeader().getVIN(), result.toJSONString());
            }
        }
        log.info("count = {}", count);
        log.info("successCount = {}", successCount);
    }

    /**
     *  发送请求
     * @param param
     * @return
     */
    public static Response sendHttp(String param) throws IOException {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, param);
        Request request = new Request.Builder()
                .url(URL)
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .build();
        Response response = client.newCall(request).execute();
        return response;
    }
}
